'''
Author: wangjq4214
Date: 2022-04-29 17:50:00
LastEditTime: 2022-05-01 22:40:47
LastEditors: wangjq4214
'''
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.controller import include_router
from app.db import Base, SessionLocal
from app.middleware import exception_handler
from app.dao.user import create_root_user, get_user_by_username


def check_root_user():
    db = SessionLocal()
    user = get_user_by_username(db, "root")
    if user is not None:
        return
    create_root_user(db)
    db.close()


def new_fastapi_app() -> FastAPI:
    app = FastAPI()

    # 注册中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins="*",
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    exception_handler(app)

    include_router(app)

    # 迁移数据模型
    Base.metadata.create_all()
    check_root_user()

    return app
